<template>
  <div class="app-container">
    <el-card :bordered="false">
      <el-form  ref="formValidate" :rules="ruleValidate" :model="formValidate" label-width="130px" >
        <!-- <el-row :gutter="24"> -->
          <!-- 商品信息-->
           <el-row :gutter="24">
          <!-- 商品信息-->
           <el-col v-bind="grid2">
            <el-form-item label="商铺名称：" prop="merName">
              <el-input v-model="formValidate.merName" placeholder="请输入商铺名称"  :disabled="identNumber == 2 || identNumber == 3" />
            </el-form-item>
           </el-col>
           
          <el-col v-bind="grid2">
              <el-form-item label="商铺分类" prop="cateId">
                 <el-select v-model="formValidate.cateId" clearable placeholder="请选择商铺分类" class="filter-item" style="width: 100%" :disabled="identNumber == 2 || identNumber == 3">
                   <el-option v-for="item in queryTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
              <el-form-item label="所属用户：" prop="userId">
                 <!-- <el-select v-model="formValidate.userId" clearable placeholder="请选择所属用户" class="filter-item" style="width: 100%" :disabled="identNumber != 1">
                   <el-option v-for="item in userListOptions" :key="item.uid" :label="item.username" :value="item.uid"/>
                  </el-select> -->
                   <el-autocomplete
    clearable
    class="inline-input"
    v-model="formValidate.userName"
    :fetch-suggestions="querySearch"
    placeholder="请输入所属用户"
    @select="handleSelect"
    value-key="username"
  :disabled="identNumber == 2 || identNumber == 3"
  ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
              <el-form-item label="地区：" prop="area">
                 <el-cascader ref="refSubCat"  v-model="formValidate.area"  style="width: 100%"   @change='changeHandle' :option='aaaList'  :disabled="identNumber == 2 || identNumber == 3"
                 :props="props"  :key="flag"></el-cascader>
            </el-form-item>
          </el-col>
           <el-col v-bind="grid2">
              <el-form-item label="详细地址：" prop="merAddr">
                <el-input v-model="formValidate.merAddr" placeholder="请输入详细地址"   :disabled="identNumber == 2 || identNumber == 3" />
              </el-form-item>
            </el-col>
           </el-row>
            <div>
               <el-form-item label="商户图片：" prop="merPic" style="text-align:left">
                <single-pic v-model="formValidate.merPic"  type="image" :num="1" :width="150" :height="150"  :disabled="identNumber == 2 || identNumber == 3" />
              </el-form-item>
            </div>
             <el-row>
          <el-col>
            <el-form-item label="地图：">
                <div id="container" style="width: 720px; height: 300px;"></div>
                    <div id="searchPart">
                    <el-input size="mini" style="width: 720px;" v-model="area"  type="text" id="searchInput" placeholder="请输入"  :disabled="identNumber == 2 || identNumber == 3" />
                    <el-button type="primary" size="mini" id="searchBtn" @click="handle_search">搜索</el-button>
                </div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="经纬度："><span id="position"  :disabled="identNumber == 2 || identNumber == 3">{{lat}} {{lng}}</span></el-form-item>
          </el-col>
        </el-row>
          <div >
              <el-form-item label="店铺介绍：" prop="descript" >
              <el-input type="textarea" :rows="3"  v-model="formValidate.descript" placeholder="请输入店铺介绍：" :disabled="identNumber == 2 || identNumber == 3"  />
            </el-form-item>
          </div>
           <div >
            <el-form-item label="商品详情：">
              <ueditor-wrap v-model="formValidate.introduction" :config="myConfig"  @beforeInit="addCustomDialog"  :contenteditable="identNumber != 1"></ueditor-wrap>
            </el-form-item>
          </div>
            <div class="radioAlign">
             <el-form-item label="审核结果："  prop="status" v-if="identNumber == 2 || identNumber == 3">
              <el-radio-group v-model="formValidate.status"  @change="changeSpec"  :disabled="identNumber == 3">
                <el-radio :label="1" class="radio">通过</el-radio>
                <el-radio :label="2">不通过</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
           <div >
              <el-form-item label="不通过理由：" prop="explain" v-if="formValidate.status==2">
              <el-input   v-model="formValidate.explain" placeholder="请输入不通过理由" type="textarea" :rows="3" :disabled="identNumber == 3" />
            </el-form-item>
          </div>
         <el-form-item>
          <el-button type="primary" class="submission" @click="handleSubmit('formValidate')"  v-if="identNumber !=3">提交</el-button>
          <el-button type="" class="submission" @click="handleCancel('formValidate')" v-if="identNumber !=3">取消</el-button>
          <el-button type="primary" class="submission" @click="handleBack('formValidate')" v-if="identNumber ==3">返回</el-button>

        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  add,
  getInfo,
  getArea,
  getStoreCategoryList,
  userList,
  audit,
  update,
} from "@/api/spManage";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import editor from "../../components/Editor";
import singlePic from "@/components/singlematerial";
import crudYxSystemStore from "@/api/yxSystemStore";
import $ from "jquery";
import UeditorWrap from "vue-ueditor-wrap";
const defaultCrud = CRUD({
  title: "商铺",
  url: "api/yxSystemStore",
  sort: "id,desc",
  crudMethod: { ...crudYxSystemStore },
});
export default {
  components: {
    editor,
    singlePic,
    crudYxSystemStore,
    UeditorWrap,
  },
  data() {
    return {
      spinShow: false,
      queryTypeOptions: [],
      userListOptions: [],
      userListOptions1: [],
      identNumber: "",
      area: "",
      lat: "",
      lng: "",
      aaaList: [],
      formValidate: {
        merName: "",
        merId: "",
        merPic: "",
        userId: "",
        cateId: "",
        merAddr: "",
        descript: "",
        area: ["", "", ""],
        status: 1,
        explain: "",
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        provinceName: "",
        cityName: "",
        areaName: "",
        latitude: "",
        longitude: "",
        introduction: "",
      },
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24,
      },
      grid3: {
        xl: 18,
        lg: 18,
        md: 20,
        sm: 24,
        xs: 24,
      },
      cascaderData: [],
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          if (level == 0) {
            getArea().then(res => {
              let nodes = res.map((item, index) => {
                return {
                  value: item.code,
                  label: item.name,
                  leaf: false,
                };
              });
              resolve(nodes);
            });
          } else {
            getArea({ code: node.data.value }).then(res => {
              let nodes = res.map((item, index) => {
                return {
                  value: item.code,
                  label: item.name,
                  leaf: (item.leaf = level >= 2),
                };
              });
              resolve(nodes);
            });
          }
        },
      },
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器宽度
        UEDITOR_HOME_URL: "/UEditor/",
        serverUrl: "",
      },
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,
      optionsMetaShow: [],
      watchIndex: 0,
      flag: false,
      ruleValidate: {
        merName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        store_info: [
          { required: true, message: "请输入商品简介", trigger: "blur" },
        ],
        area: [
          {
            type: "array",
            required: true,
            message: "请选择省份",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    "formValidate.area": {
      deep: true,
      handler(newValue, oldValue) {
        this.watchIndex++;
        if (this.watchIndex === 1) {
          this.flag = !this.flag;
        }
      },
    },
  },
  mounted() {
    this.getInfo();
    this.getStoreCategoryList();
    this.userList();
  },
  methods: {
    //富文本框
    addCustomDialog() {
      window.UE.registerUI(
        "yshop",
        function(editor, uiName) {
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: "/yshop/materia/index",
            editor: editor,
            name: uiName,
            title: "上传图片",
            cssRules: "width:1200px;height:500px;padding:20px;",
          });
          this.dialog = dialog;

          var btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              dialog.render();
              dialog.open();
            },
          });

          return btn;
        },
        37
      );
    },
    //商户分类列表
    getStoreCategoryList() {
      getStoreCategoryList().then(res => {
        this.queryTypeOptions = res;
      });
    },

    //所属用户列表
    userList() {
      // userList().then(res => {
      //   this.userListOptions = res.data;
      // });
    },
    changeHandle(event) {
      this.formValidate.provinceName = this.$refs[
        "refSubCat"
      ].getCheckedNodes()[0].parent.parent.label;
      this.formValidate.cityName = this.$refs[
        "refSubCat"
      ].getCheckedNodes()[0].parent.label;
      this.formValidate.areaName = this.$refs[
        "refSubCat"
      ].getCheckedNodes()[0].label;
    },
    // 详情
    getInfo() {
      let that = this;
      console.log(that.$route.params);
      let id = that.$route.params.id || 0;
      that.identNumber = that.$route.query.identNumber;
      getInfo(id).then(async res => {
        let data = res;
        if (data) {
          that.formValidate = data;
          console.log(that.formValidate, "wode");
          that.lat = data.latitude;
          that.lng = data.longitude;
          that.formValidate.cateId = Number(data.cateId);
          that.$set(that.formValidate, "area", [
            data.provinceCode,
            data.cityCode,
            data.areaCode,
          ]);
          //编辑
          if (this.identNumber == 2) {
            this.formValidate.status = 1;
          } else {
            this.formValidate.status = Number(data.status);
            this.formValidate.explain = data.mexplain;
          }
        }
      });
      that.initMap();
    },
    initMap() {
      var that = this;
      var center = new TMap.LatLng(39.984104, 116.307503); //设置中心点坐标
      //初始化地图
      var map = new TMap.Map("container", {
        center: center,
      });
      //绑定点击事件
      map.on("click", function(evt) {
        that.lat = evt.latLng.getLat().toFixed(6);
        that.lng = evt.latLng.getLng().toFixed(6);
        that.formValidate.latitude = that.lat;
        that.formValidate.longitude = that.lng;
      });
    },
    handle_search() {
      var that = this;
      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: {
          key: "G36BZ-CFXRS-WF4OL-6BE3X-6756F-UUBMF", // 填申请到的key
          address: encodeURI(that.area), //具体的地址
          output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function(json) {
          if (json.status == 0) {
            that.lat = json.result.location.lat;
            that.lng = json.result.location.lng;
          } else {
            console.log("错误信息：", json.message);
          }
        },
        error: function(err) {
          console.log("异常错误，请刷新浏览器后重试");
        },
      });
    },
    querySearch(queryString, cb) {
      userList().then(res => {
        this.userListOptions = res.data;
        var results = queryString
          ? this.userListOptions.filter(this.createFilter(queryString))
          : this.userListOptions;
        // 调用 callback 返回建议列表的数据
        cb(results);
      });
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.username
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      this.formValidate.userId = item.uid;
      this.formValidate.userName = item.username;
    },
    // 改变审核结果
    changeSpec(e) {
      console.log(e);
    },
    // 提交
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          //添加
          if (this.identNumber == 1) {
            this.formValidate.provinceCode = this.formValidate.area[0];
            this.formValidate.cityCode = this.formValidate.area[1];
            this.formValidate.areaCode = this.formValidate.area[2];
            add(this.formValidate)
              .then(async res => {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.push({ path: "/spManage/spList" });
                }, 500);
              })
              .catch(res => {
                // this.$message({
                //   message:res.message,
                //   type: 'error'
                // });
              });
          } else if (this.identNumber == 2) {
            console.log(this.formValidate);
            //审核
            audit(this.formValidate)
              .then(async res => {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.push({ path: "/spManage/spList" });
                }, 500);
              })
              .catch(res => {
                // this.$message({
                //   message:res.message,
                //   type: 'error'
                // });
              });
          } else if (this.identNumber == 4) {
            //编辑
            this.formValidate.provinceCode = this.formValidate.area[0];
            this.formValidate.cityCode = this.formValidate.area[1];
            this.formValidate.areaCode = this.formValidate.area[2];
            console.log(this.formValidate);
            update(this.formValidate)
              .then(async res => {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.push({ path: "/spManage/spList" });
                }, 500);
              })
              .catch(res => {
                // this.$message({
                //   message:res.message,
                //   type: 'error'
                // });
              });
          }
        }
      });
    },

    // 取消-清空表单
    handleCancel(name) {
      if (this.identNumber == 1 ||this.identNumber == 4) {
        this.formValidate.merName = "";
        this.formValidate.cateId = "";
        this.formValidate.merAddr = "";
        this.formValidate.descript = "";
        this.formValidate.area = [];
        this.formValidate.merPic = "";
        this.formValidate.userId = "";
        this.formValidate.status = "";
        this.formValidate.introduction = "";
         this.formValidate.userName = "";
        this.lat = "";
        this.lng = "";
      }
    },
    handleBack() {
      this.$router.push({ path: "/spManage/spList" });
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
  },
};
</script>

<style scoped lang="stylus">
.el-autocomplete {
  width: 100%;
}

.el-form-item--small.el-form-item {
  margin-bottom: 20px;
}

.submission {
  margin-left: 10px;
}

.color-list .tip {
  color: #c9c9c9;
}

.color-list .color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #fff;
  margin-right: 10px;
}

.color-list .color-item.blue {
  background-color: #1E9FFF;
}

.color-list .color-item.yellow {
  background-color: rgb(254, 185, 0);
}

.color-list .color-item.green {
  background-color: #009688;
}

.columnsBox {
  margin-right: 10px;
}

.priceBox {
  width: 100%;
}

.rulesBox {
  display: flex;
  flex-wrap: wrap;
}

.curs {
  cursor: pointer;
}
</style>
